package com.demo.arch.datapulsedemo.v2_pipeline.steps;

import com.demo.arch.datapulsedemo.common.MockOrderMapper;
import com.demo.arch.datapulsedemo.common.OrderData;
import com.demo.arch.datapulsedemo.v2_pipeline.core.PipelineContext;
import com.demo.arch.datapulsedemo.v2_pipeline.core.StepExecutionException;
import com.demo.arch.datapulsedemo.v2_pipeline.core.StepHandler;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.List;

/**
 * 步骤1：数据查询处理器
 * 
 * 职责：
 * - 根据报表类型查询订单数据
 * - 将数据保存到Context中
 * 
 * @author DataPulse Team
 */
@Slf4j
@Component
public class DataQueryStepHandler implements StepHandler {

  @Autowired
  private MockOrderMapper orderMapper;

  @Override
  public String getName() {
    return "数据查询";
  }

  @Override
  public int getOrder() {
    return 1;
  }

  @Override
  public void handle(PipelineContext context) throws StepExecutionException {
    log.info(">>> [{}] 开始执行", getName());

    try {
      String reportType = context.getReportType();

      // 查询数据
      List<OrderData> orderList = orderMapper.selectByReportType(reportType);

      // 保存到Context
      context.setOrderData(orderList);

      log.info(">>> [{}] 完成，查询到 {} 条数据", getName(), orderList.size());

      // 打印样例数据
      if (!orderList.isEmpty()) {
        log.info("样例数据:");
        for (int i = 0; i < Math.min(3, orderList.size()); i++) {
          OrderData sample = orderList.get(i);
          log.info("  {} | {} | {} | {}",
              sample.getOrderNo(),
              sample.getCustomerName(),
              sample.getAmount(),
              sample.getStatus());
        }
      }

    } catch (Exception e) {
      log.error(">>> [{}] 执行失败", getName(), e);
      throw new StepExecutionException(getName(), "数据查询失败", e);
    }
  }

  @Override
  public boolean shouldExecute(PipelineContext context) {
    // 幂等性检查：如果数据已存在，跳过执行
    if (context.getOrderData() != null && !context.getOrderData().isEmpty()) {
      log.info(">>> [{}] 数据已存在，跳过执行", getName());
      return false;
    }
    return true;
  }
}
